package com.qll123.module_aop.tracking;

import android.util.Log;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.json.JSONObject;

import java.lang.annotation.Annotation;

/**
 * @author lyg
 */
@Aspect
public class TrackEventAspectJInjector {

    @Pointcut("execution(@com.qll123.module_aop.tracking.TrackEvent * *(..))")
    public void trackEvent(){
        Log.e("TrackEventAspectJ","trackEvent");
    }

    @Around("trackEvent()")
    public void trackEventAroud(ProceedingJoinPoint joinPoint) throws Throwable{
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        //获取方法上的注解

        TrackEvent trackEvent  = methodSignature.getMethod().getAnnotation(TrackEvent.class);

        String evetName = trackEvent.eventName();
        String evetId = trackEvent.eventId();

        JSONObject params = new JSONObject();
        params.put("eventName",evetName);
        params.put("eventId",evetId);

        //获取方法参数的注解
        Annotation[][] annotations = methodSignature.getMethod().getParameterAnnotations();
        if (annotations.length!=0){
            int i = 0;
            for (Annotation[] paramerannotation:annotations){
                for (Annotation annotation:paramerannotation){
                    if (annotation instanceof TrackParameter){
                        String key = ((TrackParameter) annotation).value();
                        params.put(key,joinPoint.getArgs()[i++]);
                    }
                }

            }
        }
        // 上报
        Log.e("weilu", "上报数据---->" + params.toString());
        try {
            joinPoint.proceed();
        }catch (Throwable e){
            e.printStackTrace();
        }
    }
}
